package com.ac.service;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ac.cron.CronManager;
import com.ac.model.Cron;
import com.ac.model.Page;
import com.ac.model.query.CronQ;
import com.ac.util.MongoUtil;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class CronService {

	final MongoTemplate mongo;

	public Page list(CronQ uq) {
		return MongoUtil.findPge(uq, Cron.class);
	}

	@Transactional(rollbackFor = Exception.class)
	public void insert(Cron cron) {
		cron.insert();
		mongo.insert(cron);
		if (cron.isStatus())
			CronManager.run();
	}

	@Transactional(rollbackFor = Exception.class)
	public void update(Cron cron) {
		cron.update();
		Criteria criteria = Criteria.where("id").is(cron.getId());
		Cron cronInfo = mongo.findOne(Query.query(criteria), Cron.class);
		Query query = Query.query(criteria);
		Update update = new Update();
		update.set("parentId", cron.getParentId());
		update.set("status", cron.isStatus());
		update.set("cron", cron.getCron());
		update.set("funStr", cron.getFunStr());
		update.set("desc", cron.getDesc());
		update.set("updateTime", cron.getUpdateTime());
		mongo.updateFirst(query, update, Cron.class);
		if (cronInfo != null) {
			if (cronInfo.isStatus() != cron.isStatus())
				CronManager.run();
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public void remove(Cron cron) {
		mongo.remove(cron);
		CronManager.run();
	}

}
